#include <iostream>
#include <boost/asio.hpp>
#include <boost/bind/bind.hpp>
#include <string>
#include <memory>
#include <vector>

// Boost.Asio 异步操作示例
// 演示各种异步编程模式

class AsyncOperationsDemo {
private:
    boost::asio::io_context& io_;
    boost::asio::steady_timer timer_;
    int operation_count_;

public:
    AsyncOperationsDemo(boost::asio::io_context& io)
        : io_(io), timer_(io), operation_count_(0) {}

    // 示例1: 使用 lambda 表达式的异步操作
    void lambda_async_example() {
        std::cout << "\n=== Lambda Async Example ===" << std::endl;

        timer_.expires_after(std::chrono::seconds(1));
        timer_.async_wait([this](const boost::system::error_code& ec) {
            if (!ec) {
                std::cout << "Lambda timer expired!" << std::endl;
                this->chain_async_operations();
            }
        });
    }

    // 示例2: 链式异步操作
    void chain_async_operations() {
        std::cout << "\n=== Chained Async Operations ===" << std::endl;

        operation_count_ = 0;
        perform_next_operation();
    }

private:
    void perform_next_operation() {
        if (operation_count_ < 3) {
            timer_.expires_after(std::chrono::milliseconds(500));
            timer_.async_wait([this](const boost::system::error_code& ec) {
                if (!ec) {
                    ++operation_count_;
                    std::cout << "Chained operation " << operation_count_ << " completed" << std::endl;
                    this->perform_next_operation(); // 递归调用下一个操作
                }
            });
        } else {
            std::cout << "All chained operations completed!" << std::endl;
            parallel_async_example();
        }
    }

public:
    // 示例3: 并行异步操作
    void parallel_async_example() {
        std::cout << "\n=== Parallel Async Operations ===" << std::endl;

        auto completion_counter = std::make_shared<int>(0);
        const int total_operations = 3;

        for (int i = 0; i < total_operations; ++i) {
            auto timer = std::make_shared<boost::asio::steady_timer>(io_);
            timer->expires_after(std::chrono::milliseconds(1000 + i * 200));

            timer->async_wait([this, i, completion_counter, total_operations, timer]
                             (const boost::system::error_code& ec) {
                if (!ec) {
                    std::cout << "Parallel operation " << (i + 1) << " completed" << std::endl;
                    (*completion_counter)++;

                    if (*completion_counter == total_operations) {
                        std::cout << "All parallel operations completed!" << std::endl;
                        this->error_handling_example();
                    }
                }
            });
        }
    }

    // 示例4: 错误处理
    void error_handling_example() {
        std::cout << "\n=== Error Handling Example ===" << std::endl;

        // 模拟一个会被取消的操作
        timer_.expires_after(std::chrono::seconds(5));
        timer_.async_wait([this](const boost::system::error_code& ec) {
            if (ec == boost::asio::error::operation_aborted) {
                std::cout << "Operation was cancelled (expected)" << std::endl;
            } else if (ec) {
                std::cout << "Unexpected error: " << ec.message() << std::endl;
            } else {
                std::cout << "Operation completed normally (unexpected)" << std::endl;
            }

            this->completion_handler_example();
        });

        // 立即取消操作来演示错误处理
        boost::asio::post(io_, [this]() {
            timer_.cancel();
        });
    }

    // 示例5: 自定义完成处理器
    void completion_handler_example() {
        std::cout << "\n=== Custom Completion Handler Example ===" << std::endl;

        timer_.expires_after(std::chrono::milliseconds(500));
        timer_.async_wait(CustomHandler("Custom handler operation"));
    }

private:
    // 自定义完成处理器类
    class CustomHandler {
    private:
        std::string name_;

    public:
        CustomHandler(const std::string& name) : name_(name) {}

        void operator()(const boost::system::error_code& ec) {
            if (!ec) {
                std::cout << name_ << " completed successfully!" << std::endl;
            } else {
                std::cout << name_ << " failed: " << ec.message() << std::endl;
            }
        }
    };
};

// 工作队列示例
class WorkQueue {
private:
    boost::asio::io_context& io_;
    boost::asio::steady_timer timer_;
    std::vector<std::string> tasks_;
    size_t current_task_;

public:
    WorkQueue(boost::asio::io_context& io)
        : io_(io), timer_(io), current_task_(0) {

        tasks_ = {
            "Processing task 1: Database query",
            "Processing task 2: File I/O operation",
            "Processing task 3: Network request",
            "Processing task 4: Data analysis",
            "Processing task 5: Report generation"
        };
    }

    void start_processing() {
        std::cout << "\n=== Work Queue Example ===" << std::endl;
        std::cout << "Starting to process " << tasks_.size() << " tasks..." << std::endl;

        process_next_task();
    }

private:
    void process_next_task() {
        if (current_task_ < tasks_.size()) {
            std::cout << tasks_[current_task_] << "..." << std::endl;

            // 模拟任务处理时间
            timer_.expires_after(std::chrono::milliseconds(800));
            timer_.async_wait([this](const boost::system::error_code& ec) {
                if (!ec) {
                    std::cout << "Task " << (current_task_ + 1) << " completed!" << std::endl;
                    ++current_task_;
                    this->process_next_task();
                }
            });
        } else {
            std::cout << "All tasks completed!" << std::endl;
        }
    }
};

int main() {
    try {
        std::cout << "=== Boost.Asio Async Operations Examples ===" << std::endl;

        boost::asio::io_context io;

        // 创建演示对象
        AsyncOperationsDemo demo(io);
        WorkQueue work_queue(io);

        // 启动异步操作演示
        demo.lambda_async_example();

        // 延迟启动工作队列演示
        boost::asio::steady_timer delay_timer(io);
        delay_timer.expires_after(std::chrono::seconds(5));
        delay_timer.async_wait([&work_queue](const boost::system::error_code& ec) {
            if (!ec) {
                work_queue.start_processing();
            }
        });

        std::cout << "Starting event loop..." << std::endl;
        std::cout << "Watch the async operations execute!" << std::endl;

        // 运行事件循环
        io.run();

        std::cout << "\nAll async operations completed!" << std::endl;

    } catch (std::exception& e) {
        std::cerr << "Exception: " << e.what() << std::endl;
    }

    return 0;
}
